package com.mail.core;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import com.mail.util.Base64Encoding;
import com.mail.util.QuotedPrintable;

public class MulitPart {
	private String fileName;
	private byte[] bytes;
	private String charset;
	private String transferEncoding;

	private String localPath;

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	/**
	 * save mutipart as file
	 * 
	 * @param path
	 */
	public boolean saveAs(String path) {
		if (bytes != null) {
			try {
				FileOutputStream fout = new FileOutputStream(new File(path));
				try {
					fout.write(bytes);
					fout.close();
					return true;
				} catch (IOException e) {

					e.printStackTrace();
				}
			} catch (FileNotFoundException e) {

				e.printStackTrace();
			}

		}
		return false;
	}

	public MulitPart() {

	}

	private String content;

	public MulitPart(String content) {
		this.setContent(content);
	}

	public String toString() {
		return fileName;

	}

	public MulitPart(byte[] bytes) {
		this.bytes = bytes;
	}

	// just for large mutifile
	public MulitPart(String realPath, String fileName) {
		this.setLocalPath(realPath);
		this.fileName = fileName;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public String getContent() {
		if (charset != null && transferEncoding != null && content != null) {
			if (transferEncoding.equals("base64")) {
				byte[] bytes = Base64Encoding.base64ToByteArray(content);
				try {
					content = new String(bytes, charset.trim());
				} catch (UnsupportedEncodingException e) {

					e.printStackTrace();
				}
			} else {
				if (null != content) {
					byte[] bytes;
					try {
						bytes = content.getBytes(charset.trim());
					} catch (UnsupportedEncodingException e) {

						e.printStackTrace();
						bytes = content.getBytes();
					}
					content = QuotedPrintable.decode(bytes, charset.trim());
				}
			}
		}
		return content;
	}

	public String getCharset() {
		return charset;
	}

	public void setCharset(String charset) {
		this.charset = charset;
	}

	public String getTransferEncoding() {
		return transferEncoding;
	}

	public void setTransferEncoding(String transferEncoding) {
		this.transferEncoding = transferEncoding;
	}

	public void setLocalPath(String localPath) {
		this.localPath = localPath;
	}

	public String getLocalPath() {
		return localPath;
	}

}
